package dbops

import (
	"video/api/defs"
	"strconv"
	"sync"
)

func InsertSession(sid string, ttl int64, un string) error {
	stmt, e := conn.Prepare("insert into sessions VALUES (?,?,?)")
	if e != nil {
		return e
	}
	defer stmt.Close()
	_, e1 := stmt.Exec(sid, ttl, un)
	return e1
}

func RetrieveSession(sid string) (*defs.Session, error) {
	var ss defs.Session
	stmt, e := conn.Prepare("select id,ttl,login_name as name from sessions where sid = ?")
	if e != nil {
		return &ss, e
	}
	defer stmt.Close()
	var (
		id   string
		ttl  string
		name string
	)
	e1 := stmt.QueryRow(sid).Scan(&id, &ttl, &name)
	if e1 != nil {
		return &ss, e1
	}
	i, _ := strconv.ParseInt(ttl, 10, 64)
	ss = defs.Session{
		Id:        id,
		TTL:       i,
		LoginName: name,
	}
	return &ss, nil
}

func RetrieveAllSession() (*sync.Map, error) {
	var m *sync.Map
	stmt, e := conn.Prepare("select id,ttl,login_name as name from sessions")
	if e != nil {
		return m, e
	}
	defer stmt.Close()
	rows, e2 := stmt.Query()
	if e2 != nil {
		return m, e2
	}
	var (
		id   string
		ttl  string
		name string
	)
	for rows.Next() {
		rows.Scan(&id, &ttl, &name)
		i, _ := strconv.ParseInt(ttl, 10, 64)
		ss := defs.Session{
			Id:        id,
			TTL:       i,
			LoginName: name,
		}
		m.Store(id, ss)
	}
	return m, nil
}

func DeleteSession(sid string) error {
	stmt, e := conn.Prepare("delete from sessions where sid = ?")
	if e != nil {
		return e
	}
	defer stmt.Close()
	_, e1 := stmt.Exec(sid)
	return e1
}
